package cn.metona.mq.core;

import java.io.Serial;
import java.time.LocalDateTime;
import java.io.Serializable;

/**
 * 队列中的消息包装类
 * 包含消息状态和处理信息
 */
public class QueueMessage implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    private final Message message;              // 消息内容
    private volatile boolean consumed;          // 是否已被消费
    private volatile boolean acked;             // 是否已确认
    private volatile int retryCount;            // 重试次数
    private volatile LocalDateTime firstConsumeTime; // 首次消费时间
    private volatile LocalDateTime lastConsumeTime;  // 最后消费时间
    private volatile String consumerId;         // 消费者ID

    /**
     * 构造函数
     */
    public QueueMessage(Message message) {
        if (message == null) {
            throw new IllegalArgumentException("Message cannot be null");
        }
        this.message = message;
        this.consumed = false;
        this.acked = false;
        this.retryCount = 0;
    }

    // Getter和Setter方法
    public Message getMessage() {
        return message;
    }

    public boolean isConsumed() {
        return consumed;
    }

    public void setConsumed(boolean consumed) {
        this.consumed = consumed;
        if (consumed && firstConsumeTime == null) {
            firstConsumeTime = LocalDateTime.now();
        }
        if (consumed) {
            lastConsumeTime = LocalDateTime.now();
        }
    }

    public boolean isAcked() {
        return acked;
    }

    public void setAcked(boolean acked) {
        this.acked = acked;
    }

    public int getRetryCount() {
        return retryCount;
    }

    public synchronized void incrementRetryCount() {
        this.retryCount++;
    }

    public LocalDateTime getFirstConsumeTime() {
        return firstConsumeTime;
    }

    public LocalDateTime getLastConsumeTime() {
        return lastConsumeTime;
    }

    public String getConsumerId() {
        return consumerId;
    }

    public void setConsumerId(String consumerId) {
        this.consumerId = consumerId;
    }

    /**
     * 重置消费状态（用于重试）
     */
    public void resetConsumeState() {
        this.consumed = false;
        this.acked = false;
        this.consumerId = null;
    }

    /**
     * 获取消息ID
     */
    public String getMessageId() {
        return message.messageId();
    }

    /**
     * 判断是否需要重试（基于重试次数）
     */
    public boolean shouldRetry(int maxRetries) {
        return retryCount < maxRetries;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        QueueMessage that = (QueueMessage) o;
        return getMessageId().equals(that.getMessageId());
    }

    @Override
    public int hashCode() {
        return getMessageId().hashCode();
    }
}